/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pop3;

import java.util.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;



public class Client extends JFrame
{


  class PopMessage {

    public String message;
    private String title;

    public PopMessage (String titleW, String msg)
    {
      title = titleW;
      message = msg;
    }

    @Override
    public String toString()
    {
      return title;
    }

  }

  public class PopServerDialog extends JDialog
  {
    JTextField hostTF, portTF, userTF;
    JPasswordField passwordTF;

    public PopServerDialog(Frame parent, boolean modal)
    {
      super(parent, modal);

      JPanel panel1, panel2, panel3;
      JButton okButton, cancelButton;

      Container contentPane = this.getContentPane();

      panel1 = new JPanel();
      panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add(panel1, BorderLayout.SOUTH);
      okButton = new JButton("OK");
      panel1.add(okButton);
      cancelButton = new JButton("Cancel");
      panel1.add(cancelButton);

      panel3 = new JPanel();
      panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add(panel3, BorderLayout.CENTER);
      hostTF = new JTextField(popServer, 20);
      portTF = new JTextField("" + port, 5);
      panel3.add(new JLabel("Server"));
      panel3.add(hostTF);
      panel3.add(new JLabel("Port"));
      panel3.add(portTF);

      panel2 = new JPanel();
      panel2.setLayout(new FlowLayout(FlowLayout.CENTER));
      contentPane.add(panel2, BorderLayout.NORTH);
      userTF = new JTextField(user, 20);
      passwordTF = new JPasswordField(password, 10);
      panel2.add(new JLabel("User"));
      panel2.add(userTF);
      panel2.add(new JLabel("Passwd"));
      panel2.add(passwordTF);

      setTitle("Pop Server info");
      pack();


      cancelButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event)
        {
          dispose();
          setVisible(false);
        }
      });

      okButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event)
        {
          popServer = hostTF.getText();
          user = userTF.getText();
          password = new String(passwordTF.getPassword());

          port = Integer.parseInt(portTF.getText());
          dispose();
          setVisible(false);
        }
      });

    }
  }

  private String popServer = "localhost";
  private String user = "test" , password = "admin";
  private int port = 110;

  private JLabel status = new JLabel("Ready...");
  private JTextArea Jbody = new JTextArea(10,20);
  private Vector messages = new Vector();
  private JList msgList = new JList();

  public Client ()
  {
    JMenuBar menuBar = new JMenuBar();

    JPanel statusbar = new JPanel();
    JPanel Core = new JPanel();
    JScrollPane SPbody, SPlist;

    Core.setLayout(new BorderLayout());

    Container contentPane = this.getContentPane();
    contentPane.setLayout(new BorderLayout());

    setJMenuBar(menuBar);

    JMenu fMenu = new JMenu("File");
    menuBar.add(fMenu);

    JMenuItem popServerItem = new JMenuItem("Set Pop Server", 2);
    fMenu.add(popServerItem);
    JMenuItem popMsgItem = new JMenuItem("Get Messages", 2);
    fMenu.add(popMsgItem);
    fMenu.addSeparator();
    JMenuItem exitItem = new JMenuItem("Exit", 2);
    fMenu.add(exitItem);

    statusbar.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
    statusbar.setBorder(new BevelBorder(BevelBorder.LOWERED));
    contentPane.add(statusbar,BorderLayout.SOUTH );
    statusbar.add(status);


    SPbody = new JScrollPane(Jbody,
                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    SPlist = new JScrollPane(msgList,
                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    Core.add(SPlist, BorderLayout.WEST);
    Core.add(SPbody, BorderLayout.EAST);

    contentPane.add(Core);


    // add listeners for the window and the various buttons
    this.addWindowListener( new WindowAdapter(){
         public void windowClosing(WindowEvent e){
              setVisible(false);
              dispose();
              System.exit(0);
    }});

    exitItem.addActionListener( new ActionListener(){
         public void actionPerformed(ActionEvent e){
              System.exit(0);
    }});

    popMsgItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            getMessages();
    }});

    popServerItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            changePopServer();
    }});

    msgList.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            int index = msgList.locationToIndex(e.getPoint());
            if ( index >= 0 && index < messages.size())
              Jbody.setText(((PopMessage)messages.elementAt(index)).message);
        }
    });

    pack();

  }

  protected void getMessages()
  {
      PrintWriter to;
      BufferedReader from;
      String str,title, msg;
      Vector v = new Vector();

      try {
        Socket socket = new Socket(InetAddress.getByName(popServer),port);

        to = new PrintWriter(
                    new BufferedWriter (
                        new OutputStreamWriter (
                            socket.getOutputStream())),true);
        from = new BufferedReader(
                   new InputStreamReader (
                            socket.getInputStream()));
        //System.out.println(from.readLine());

        while ( ! (from.readLine()).startsWith("+OK") );
        to.println("USER "+user);
        while ( ! (from.readLine()).startsWith("+OK") );
        to.println("PASS "+password);
        while ( ! (from.readLine()).startsWith("+OK") );

        to.println("LIST");
        while ( ! (from.readLine()).startsWith("+OK") );
        do {
          str = from.readLine();
          if ( str.compareTo(".") != 0 ) v.add(str);
        } while ( str.compareTo(".") != 0 );

        for ( int i =0; i < v.size(); i++ ) {
          title = (String ) v.elementAt(i);
          to.println("RETR "+(new StringTokenizer(title)).nextToken()+"\r");
          while ( ! (from.readLine()).startsWith("+OK") );
          msg = "";
          do {
            msg += from.readLine() + "\n";
          } while ( ! msg.endsWith("\n.\n") );
          messages.add(new PopMessage(title, msg));
        }

        msgList.setListData(messages);

        status.setText("Ready ...");

        socket.close();

      } catch ( Exception e ) {System.err.println(e);}


  }

  protected void changePopServer()
  {
    new PopServerDialog(this, true).show();
  }

  public static void main ( String args[] )
  {
      try {
          new Serveur().start();
        (new Client()).setVisible(true);
      } catch (IOException ex) {
          Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
      }

  }

}